package com.wt.springsamples.es;


import com.wt.springsamples.es.client.TransportUtils;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchProperties;
import org.springframework.boot.autoconfigure.elasticsearch.RestClientBuilderCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;

@Configuration
@EnableConfigurationProperties({ElasticsearchProperties.class})
public class EsConfiguration{

//    private ElasticsearchProperties properties;
//    EsConfiguration(ElasticsearchProperties properties){
//        this.properties = properties;
//    }
//    @Override
//    public ClientConfiguration clientConfiguration() {
//        return ClientConfiguration.builder()
//                .connectedTo("localhost:9200")
//                .build();
//    }

    @Bean
    public RestClientBuilderCustomizer restClientBuilderCustomizer(ElasticsearchProperties properties) throws IOException {
        File certFile = new File("D:/java-env/elk/elasticsearch-8.14.2/config/certs/http_ca.crt");
        SSLContext sslContext = TransportUtils.sslContextFromHttpCaCrt(certFile);

        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
                AuthScope.ANY, new UsernamePasswordCredentials(properties.getUsername(), properties.getPassword())
        );

        return builder -> {
            builder.setHttpClientConfigCallback(hc -> hc
                    .setSSLContext(sslContext)
                    .setDefaultCredentialsProvider(credentialsProvider)
            );
        };
    }

}
